<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>一笔画地图编辑器</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
<style>
html, body, p, div {margin:0;padding:0;}
</style>
</head>
<body>
<canvas id='canvas'></canvas>
<script type="text/javascript" src="../libs/minicomps.min.js"></script>
<script src="../libs/easeljs.js"></script>
<script>
    const { Toggle, HSlider,VSlider,Panel, Canvas ,Button,TextArea,TextBox,TextInput,Label,Window,Image,LabelInput,TipsManager,RadioButton,ColorPicker,TabbarWindow,Checkbox,Knob,Stage,MoonTextArea,Dropdown} = mc
	const SAVE_NAME='drawLine';
    const SAVE_NAME_ANS='drawLine_ans';
    canvas=document.getElementById('canvas');
    canvas.style.backgroundColor = '#999999';
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;
    var stage=new createjs.Stage(canvas);
    let layer=new createjs.Container();
    layer.x=layer.y=10;
    stage.addChild(layer);
    var xnum=Number(localStorage.getItem("drawLineNum")||10);
    var ynum=xnum;
    var wid=Number(localStorage.getItem("drawLineWid")||50);
    var maps=[];
    var state=0;
    var prev=null;
    var points=[];
    var answerLinePoints=[];
    var answerPoints=[];
    var myDrawPoints=[];
    var myLineTemps=[];
    var titleLines=[];
    var radius=5;
    var radius2=radius*2;
    var line;
    let names=['加点','连接','测试','清除','保存','读取','删除线条或点'];
    for(let i=0;i<names.length;i++){
        new Button(document.body,600,60+i*30,names[i],(e)=>{
            state=names.indexOf(e.target.label);
            prev=null;
            line=null;
            //console.log(state);
            if(state==3){
                document.location.reload();
            }else if(state==4){
                save();
            }else if(state==5){
                read();
            }
            titleLines.forEach((line)=>{line.removeEventListener('mousedown',this.removeLine);})
            if(state==6){
                titleLines.forEach((line)=>{line.addEventListener('mousedown',this.removeLine);})
            }
        });
    }
    let txt=new TextInput(document.body,600,10);
    new Label(document.body,600,32,'当输入一个数时例如8表示x轴y轴都是8个点,当输入两个数时例如8,50表示x轴y轴都是8个点而点之间的距是50')
    new Button(document.body,700,10,'确定',(e)=>{
        var num=txt.text.split(',')
        if(num.length==2){//只输入num代表x,y轴数量,输入num,num第一个代表x,y轴数量第二个代表两点间隔
            localStorage.setItem("drawLineWid",num[1]);
        }
        localStorage.setItem("drawLineNum",num[0]);
        document.location.reload();
    });

    let txt1=new TextInput(document.body,600,270);
    new Label(document.body,600,292,'把配置数据拷贝到这里可以生成游戏')
    new Button(document.body,700,270,'确定',(e)=>{
        var str=txt1.text;
        try{
            var data=JSON.parse(str);
            drawMap(data);
        }catch(e){
            alert('JSON数据错误也可能是当前圆点数不足');
        }
    });

    let txt2=new TextInput(document.body,600,330);
    new Label(document.body,600,352,'把配置数据答案拷贝到这里可以生成解题过程')
    new Button(document.body,700,330,'确定',(e)=>{
        var str=txt2.text;
        this.playAns=str.split(',');
        this.playAnsIndex=0;
        if(this.playAns.length>2){
            playAnswer();
        }else{
            alert('空数据')
        }
    });

    stage.addEventListener('stagemousemove',(e)=>{
        onLine(e);
    })
    stage.addEventListener('stagemouseup',(e)=>{
        onLine(e);
    })
    createView();
    function createView(){
        for(var i=0;i<ynum;i++){
            var ms=[];
            for(var j=0;j<xnum;j++){
                var box=createCircle(wid,wid,radius,'#ffffff',false);
                box.x=j*wid;
                box.y=i*wid;
                box.pos=j+','+i;
                ms.push(box);
            }
            maps.push(ms);
        }
    }
    function createCircle(w,h,r,c,b=true){
        var sp=new createjs.Shape;
        b&&sp.graphics.setStrokeStyle(1).beginStroke('black');
        sp.graphics.beginFill(c);
        sp.graphics.drawCircle(0,0,r)
        sp.width=w,sp.height=h;
        sp.addEventListener('mousedown',addBlackHandler);
        layer.addChild(sp);
        return sp;
    }
    function addBlackHandler(e){
        var sp=e.target;
        let c='#ffff00'
        if(state==0){
            sp.graphics.clear();
            sp.graphics.beginFill(c);
            sp.graphics.drawCircle(0,0,radius2);
            points.push(sp);
            answerPoints.push(sp.pos);
        }else if(state==1||state==2){
            if(prev==null){
                prev=sp;
                line=new createjs.Shape;
                layer.addChild(line);
            }
        }
        if(state==6){
            sp.graphics.clear();
            sp.graphics.beginFill('#ffffff');
            sp.graphics.drawCircle(0,0,radius);
            let li=points.indexOf(sp);
            if(li>=0) points.splice(li,1);
            li=answerPoints.findIndex((a)=>{
                return (a.toString()==sp.pos.toString());
            })
            if(li>=0) answerPoints.splice(li,1);
        }
    }
    function onLine(e){
        let [ex,ey]=[e.stageX,e.stageY];
        if(prev){
            let c=state==1?'#ffff00':'#00000';
            if(e.type=='stagemousemove'){
                line.graphics.clear();
                line.graphics.setStrokeStyle(radius2).beginStroke(c);
                line.graphics.moveTo(prev.x,prev.y);
                line.graphics.lineTo(ex,ey);
                for(let i=0;i<points.length;i++){
                    let p=points[i];
                    if(p!=prev&&Math.hypot(p.x-ex,p.y-ey)<radius2){
                        line.graphics.clear();
                        line.graphics.setStrokeStyle(radius2).beginStroke(c);
                        line.graphics.moveTo(prev.x,prev.y);
                        line.graphics.lineTo(p.x,p.y);
                        line.isOk=true;
                        if(state==1){
                            var pt=[prev.pos.split(','),p.pos.split(',')];
                            let li=answerLinePoints.findIndex((a)=>{
                                return (a[0].toString()==pt[0].toString()&&a[1].toString()==pt[1].toString()||a[0].toString()==pt[1].toString()&&a[1].toString()==pt[0].toString())
                            })
                            if(li==-1||li==undefined){
                                answerLinePoints.push(pt);
                                line.pt=pt;
                                titleLines.push(line);
                            }else{
                                layer.removeChild(line);
                            }
                        }else if(state==2){
                            myDrawPoints.push([prev.pos.split(','),p.pos.split(',')]);
                            myLineTemps.push(line);
                        }
                        prev=p;
                        line=new createjs.Shape;
                        layer.addChild(line);
                        //console.log(layer.children.length);
                    }
                }
            }else if(e.type=='stagemouseup'){
                //console.log(answerPoints,answerLinePoints)
                //console.log(state,prev);
                if(state==2){
                    let answer=answerLinePoints.toString().split(',').sort().toString();
                    let my=myDrawPoints.toString().split(',').sort().toString();
                   // console.log('answer',answer);
                   // console.log('my',my);
                    if(my==answer){
                        alert('恭喜过关');
                        let str=myDrawPoints.toString();
                        console.log(str);
                        localStorage.setItem(SAVE_NAME_ANS,str);
                        
                    }else{
                        myDrawPoints=[];
                        while(myLineTemps.length>0){
                            layer.removeChild(myLineTemps[0]);
                            myLineTemps.splice(0,1);
                        }
                    }
                }
                if(line&&!line.isOk){
                    layer.removeChild(line);
                    line=null;
                }
                prev=null;
            }
        }
    }
    function removeLine(e){
        let line=e.target;
        if(state==6){
            for(let i=0;i<points.length;i++){
                let p=points[i];
                let pt=line.pt;
                let li=answerLinePoints.findIndex((a)=>{
                    return (a[0].toString()==pt[0].toString()&&a[1].toString()==pt[1].toString()||a[0].toString()==pt[1].toString()&&a[1].toString()==pt[0].toString())
                })
                if(li>=0){
                    answerLinePoints.splice(li,1);
                    let line=titleLines.splice(li,1)[0];
                    layer.removeChild(line);
                }
            }
        } 
    }
    function save(){
        var data={p:answerPoints,l:answerLinePoints};
        localStorage.setItem(SAVE_NAME,JSON.stringify(data));
        console.log('save',JSON.stringify(data));
    }
    function read(){
        var str=localStorage.getItem(SAVE_NAME);
        try{
            var data=JSON.parse(str);
            drawMap(data);
        }catch(e){
            alert('JSON数据错误也可能是当前圆点数不足');
        }
    }
    function drawMap(data){
        var {p,l}=data;
            console.log('read',data);
            let c='#ffff00';
            points=[];
            answerLinePoints=[];
            answerPoints=[];
            titleLines=[];
            for(let i=0;i<p.length;i++){
                let pt=p[i].split(',');
                let sp=maps[pt[1]][pt[0]];
                sp.graphics.clear();
                sp.graphics.beginFill(c);
                sp.graphics.drawCircle(0,0,radius2);
                points.push(sp);
                answerPoints.push(sp.pos);
            }
            for(let i=0;i<l.length;i++){
                let pt=l[i];
                line=new createjs.Shape;
                layer.addChild(line);
                let prev=maps[pt[0][1]][pt[0][0]];
                let p=maps[pt[1][1]][pt[1][0]];
                line.graphics.setStrokeStyle(radius2).beginStroke(c);
                line.graphics.moveTo(prev.x,prev.y);
                line.graphics.lineTo(p.x,p.y);
                pt=[prev.pos.split(','),p.pos.split(',')];
                answerLinePoints.push(pt);
                line.pt=pt;
                titleLines.push(line);
            }
    }
    //4,1,5,2,5,2,6,1,6,1,6,3,6,3,4,3,4,3,4,1,4,1,6,1
    function playAnswer(){
        let pt=[];
        for(let i=0;i<2;i++){
            pt.push([this.playAns[this.playAnsIndex+i*2],this.playAns[this.playAnsIndex+i*2+1]])
        }
        let c='#ff0000';
        line=new createjs.Shape;
        layer.addChild(line);
        let prev=maps[pt[0][1]][pt[0][0]];
        let p=maps[pt[1][1]][pt[1][0]];
        line.graphics.setStrokeStyle(radius2).beginStroke(c);
        line.graphics.moveTo(prev.x,prev.y);
        line.graphics.lineTo(p.x,p.y);
        this.playAnsIndex+=2;
        if(this.playAnsIndex<this.playAns.length-2){
            setTimeout(playAnswer,300);
        }
    }
    createjs.Ticker.addEventListener("tick",(e)=>{
        stage.update();
    })
</script>
</body>
</html>